import { createBrowserRouter, Navigate, useLocation } from "react-router-dom";

//ZT
import Login from "../component/ZT/ZTlogin";
import Account from "../component/ZT/Account";
import ZTForgetPasswordLogin from "../component/ZT/wang";
import Captcha from "../component/ZT/Captcha";
import Register from "../component/ZT/Register";
import Callback from "../component/ZT/Callback";
//cws
import Yao from "../component/cws/Yao";
//cxf
import CXF from '../component/cxf/CXF'

//cyw
import CywIndex from '../component/cyw/CywIndex'
import TaskForm from "../component/cyw/TaskForm";

//yl
import YlIndex from "../component/yl/YlIndex";
import User from "../component/cws/User";

interface AuthGuardProps {
  children: React.ReactNode;
  roles?: string[];
  permissions?: string[];
}

const AuthGuard = ({ children, roles = [] }: AuthGuardProps) => {
  const location = useLocation();

  // 从 localStorage 获取用户信息（实际开发中建议使用状态管理）
  const user = JSON.parse(localStorage.getItem("user") || "{}");
  const token = localStorage.getItem("token");
  // console.log(user.roles);

  // 无 token 重定向到登录
  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  const userRoles = user.roles || [];
  // 角色校验
  const hasRole =
    roles.length > 0 ? roles.some((r) => (user.roles || []).includes(r)) : true;

  if (!hasRole) {
    return <Navigate to="/403" replace />;
  }


  return children;
};

const router = createBrowserRouter([
  //ZT
  {
    path: "/",
    element: <Navigate to="/login/account" replace />,
  },
  {
    path: "/CXF",
    element: <CXF />,
  },
  {
    path:'callback',
    element:<Callback/>
  },
  {
    path: "/login",
    element: <Login />,
    children: [
      { index: true, element: <Navigate to="account" replace /> },
      {
        path: "account",
        element: <Account />,
      },
      {
        path: "captcha",
        element: <Captcha />,
      },
      {
        path: "wang",
        element: <ZTForgetPasswordLogin />,
      },
      {
        path: "register",
        element: <Register />,
      },
    ],
  },
  // 403页面示例
  {
    path: "/403",
    element: <div>无权限访问</div>,
  },

  //cws
  {
    path: "/user",
    element: <User></User>,
  },
  {
    path: "/yao",
    element: <Yao></Yao>,
  },

  //cyw
  {
    path: '/cywindex',
    element: <CywIndex></CywIndex>
  },
  {
    path:'/task-form',
    element:<TaskForm></TaskForm>
  }
  ,
  //yl
  {
    path: "/ylindex",
    element: <YlIndex></YlIndex>
  },
  //cyw

  //yl
]);

export default router;
